package main.social.web;

import javax.servlet.http.HttpServletRequest;

import main.social.service.AccountService;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/Login")
public class LoginController {

	private AccountService accountService;

	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView login(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("");
		if (request.getSession().getAttribute("LOGEDIN_USER") == null) {
			mav.setViewName("Login");
		} else {
			mav.setViewName("Member");
		}
		return mav;
	}

	@RequestMapping(method = RequestMethod.POST)
	public String login_Submit(@RequestParam("username") String username,
			@RequestParam("password") String password,
			HttpServletRequest request) {
		if (this.accountService.Login(username, password)) {
			request.getSession().setAttribute("LOGEDIN_USER", username);
			return "redirect:Home.html";
		} 
		return "Login";
	}

	@RequestMapping(value = "/Logout")
	public ModelAndView logout(HttpServletRequest request) {
		if (request.getSession().getAttribute("LOGEDIN_USER") != null) {
			request.getSession().removeAttribute("LOGEDIN_USER");
		}
		return new ModelAndView("Home");
	}
}
